package com.bamboo.framework.framework.security.service.impl;

import com.bamboo.framework.framework.security.entity.Role;
import com.bamboo.framework.framework.security.entity.RoleMenu;
import com.bamboo.framework.framework.security.mapper.RoleMapper;
import com.bamboo.framework.framework.security.service.IRoleMenuService;
import com.bamboo.framework.framework.security.service.IRoleService;
import com.bamboo.framework.common.format.ReturnMsg;
import com.bamboo.framework.common.enums.Status;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.ArrayList;
import java.util.List;
import jodd.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 郭晴
 * @since 2018-12-15
 */
@Service

public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

  @Resource
  private IRoleMenuService iRoleMenuService;
  @Resource
  private RoleMapper roleMapper;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public ReturnMsg deleteRoleById(String id) throws Exception {

    if (StringUtil.isEmpty(id)) {
      return new ReturnMsg(Status.PARAMETER_NULL, "角色Id不能为空");
    }
    Role role = this.getById(id);
    if (role == null) {
      return new ReturnMsg(Status.DATA_DOES_NOT_EXIST, "角色不存在");
    }
    boolean roleMenu = iRoleMenuService
        .remove(new QueryWrapper<RoleMenu>().eq("roleId", role.getId()));
    if (roleMenu) {
      boolean b = this.removeById(role.getId());
      if (b) {
        return new ReturnMsg(Status.SUCCESS, "角色删除成功");
      }
      throw new Exception(RoleServiceImpl.class.getPackage() + "删除角色失败");
    }
    throw new Exception(RoleServiceImpl.class.getPackage() + "删除角色失败");
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public ReturnMsg saveRole(String id, String roleName) {

    Role role = new Role();
    if (StringUtil.isEmpty(roleName)) {
      return new ReturnMsg(Status.PARAMETER_NULL, "角色名不能为空");
    }

    role.setRoleName(roleName.trim());
    if (StringUtil.isEmpty(id)) {
      role.setCreatTime(new Date());
      role.setUpdateTime(new Date());
    } else {
      role.setId(Integer.valueOf(id).intValue());
      role.setUpdateTime(new Date());
    }
    return new ReturnMsg(Status.SUCCESS, this.saveOrUpdate(role));
  }

  @Override
  public ReturnMsg getRoleIdListByUserId(Integer userId) {
    List<Integer> ids = null;
    if (userId == null || userId < 1) {
      ids = new ArrayList<>();
    } else {
      ids = roleMapper.selectRoleIdListByUserId(userId);
    }

    return new ReturnMsg(Status.SUCCESS, ids);
  }
}
